package com.diao.myhub.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtil {
    public static String toJson(Object object){
        ObjectMapper objectMapper = SpringContextUtil.getBean(ObjectMapper.class);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    public static <T> T fromJson(String json, Class<T> clazz) throws IOException {
        ObjectMapper objectMapper = SpringContextUtil.getBean(ObjectMapper.class);
        return objectMapper.readValue(json, clazz);
    }
    public static <T> T fromJson(String json, TypeReference<T> tTypeRef) throws IOException {
        ObjectMapper objectMapper = SpringContextUtil.getBean(ObjectMapper.class);
        return objectMapper.readValue(json, tTypeRef);
    }
}
